package com.yaha.controler.devices.search;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;

import javax.jmdns.JmDNS;
import javax.jmdns.NetworkTopologyDiscovery;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;
import javax.jmdns.ServiceListener;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.yaha.controler.MyApplication;
import com.yaha.controler.devices.DeviceManager;
import com.yaha.controler.devices.pojo.MdnsDevice;
import com.yaha.controler.utils.MyLog;

public class MdnsSearchManager {
	private static final String TAG = MdnsSearchManager.class.getSimpleName();

	private static MdnsSearchManager mdnsSearchManager;
	private Context mContext;
	/**
	 * 查询类型.
	 */
	public static final String TYPE = "_easycontrol._udp.local.";
	public static final long TIMEOUT = 4 * 1000;

	/**
	 * mDNS协议java实现.
	 */
	private JmDNS jmdns;
	private ServiceListener serviceListener = null;
	/** WIfi组播锁 */
	private android.net.wifi.WifiManager.MulticastLock lock;

	private MdnsSearchManager(Context context) {
		mContext = context;
	}

	public static MdnsSearchManager newInstance(Context context) {

		if (null == mdnsSearchManager) {
			mdnsSearchManager = new MdnsSearchManager(context);
		}
		return mdnsSearchManager;
	}

	/**
	 * <功能描述>开始查询Mdns设备
	 */
	public void startMDNS() {
		Log.d(TAG, "startMDNS --->Begin");
		// 开启一个线程执行Jmdns
		new Thread() {
			public void run() {
				startJmdns();
			};
		}.start();
	}

	/**
	 * <功能描述>停止查询Mdns设备
	 */
	public void stopMDNS() {
		new Thread() {
			public void run() {
				stopJmdns();
			};
		}.start();
	}

	/**
	 * 开始jmdns查询 （最好运行在子线程）
	 */
	private void startJmdns() {
		Log.d(TAG, "startJmdns ---> ");
		try {
			stopJmdns();
			// 获取本机IP地址
			InetAddress[] addresses = NetworkTopologyDiscovery.Factory.getInstance().getInetAddresses();
			InetAddress inetAddress = null;
			MyLog.i(TAG, "addresses==" + addresses.length);
			for (int i = 0; i < addresses.length; i++) {
				if (addresses[i] instanceof Inet4Address) {
					Log.d(TAG, "addresses hostAddress=" + addresses[i].getHostAddress());
					inetAddress = addresses[i];
				}
			}
			// 创建DNS设备
			jmdns = JmDNS.create(inetAddress);
			// 创建设备监听器
			if (null == serviceListener) {
				serviceListener = new ServiceListener() {
					@Override
					public void serviceResolved(ServiceEvent event) {
						Log.d(TAG, "serviceResolved --->Begin");
					}

					@Override
					public void serviceRemoved(ServiceEvent event) {
						Log.d(TAG, "serviceRemoved --->Begin");
						ServiceInfo serviceInfo = event.getInfo();
						MdnsDevice mdnsDevice = createMdnsDevice(serviceInfo);
						// 移除Mdns设备
						DeviceManager.newInstance().removeMdnsDevice(mdnsDevice);
						String mac = serviceInfo.getPropertyString("deviceid").toLowerCase();
						String name = serviceInfo.getName();
						String ip = serviceInfo.getHostAddress();
						Log.d(TAG, "Service removed---: name = " + name + "&& ip = " + ip + " && mac = " + mac
								+ " dvb=" + serviceInfo.getPropertyString("dvb"));

					}

					@Override
					public void serviceAdded(ServiceEvent event) {
						// 打印添加设备的名称
						Log.d(TAG, "serviceAdded ---> " + event.getName());
						// jmdns得到添加的设备的信息
						ServiceInfo serviceInfo = jmdns.getServiceInfo(TYPE, event.getName());
						// 根据这些设备信息来实例化一个Mdns设备
						MdnsDevice mdnsDevice = createMdnsDevice(serviceInfo);
						// 先连接历史记录里面最后连接的设备
						DeviceManager.newInstance().connectHistoryDevice(mContext, mdnsDevice,
								MyApplication.curWifiSSID);
						Log.d(TAG, "Service add+++ : " + mdnsDevice.toString());
					}
				};
			}
			jmdns.addServiceListener(TYPE, serviceListener);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭 jmdns （最好运行在子线程）
	 * 
	 */
	private void stopJmdns() {
		Log.d(TAG, "stopJmdns --->");
		try {
			if (null != jmdns) {

				if (null != serviceListener) {
					jmdns.removeServiceListener(TYPE, serviceListener);
				}

				jmdns.close();
				jmdns = null;
				if (null != lock) {
					lock.release();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public JmDNS getJmdns() {
		return jmdns;
	}

	/**
	 * <功能描述>根据Jmdns发现的设备相应信息来实例化一个DNS设备
	 * 
	 * @param serviceInfo
	 * @return
	 */
	private MdnsDevice createMdnsDevice(ServiceInfo serviceInfo) {
		String name = "";
		String ip = "";
		String mac = "";
		MdnsDevice mdnsDevice = null;
		if (null != serviceInfo) {
			name = serviceInfo.getName();
			ip = serviceInfo.getHostAddress();
			mac = serviceInfo.getPropertyString("deviceid").toLowerCase();
			MyLog.i(TAG, "serviceInfo=" + name + "==" + ip + "==" + mac);
			Log.d(TAG, "createMdnsDevice dvb = " + serviceInfo.getPropertyString("dvb"));
			boolean dvb = false;
			if (null == serviceInfo.getPropertyString("dvb") || serviceInfo.getPropertyString("dvb").equals("false")) {
				dvb = false;
			} else if (serviceInfo.getPropertyString("dvb").equals("true")) {
				dvb = true;
			}
			MyLog.d(TAG, "Is dvb==" + dvb);
			String hardware = serviceInfo.getPropertyString("hardware");
			Log.d(TAG, "createMdnsDevice hardware = " + hardware);
			if (null == hardware || TextUtils.isEmpty(hardware)) {
				hardware = "unknow";
			}

			String model = serviceInfo.getPropertyString("model");
			Log.d(TAG, "createMdnsDevice model = " + model);
			if (null == model || TextUtils.isEmpty(model)) {
				model = "unknow";
			}

			String devType = serviceInfo.getPropertyString("devtype");
			Log.v(TAG, "createMdnsDevice devType = " + devType);

			mdnsDevice = new MdnsDevice(name, ip, mac, dvb, model, hardware);
			// 设置盒子的类型
			mdnsDevice.setDevType(devType);
		}
		return mdnsDevice;
	}
}
